from operator import itemgetter
import requests
from plotly.graph_objs import Bar
from plotly import offline

# 执行API调用并存储响应
API调用并存储响应
url = 'https://hacker-news.firebaseio.com/v0/topstories.json'
r = requests.get(url)
print(f"Status code: {r.status_code}")
# 将API响应存储在一个变量中
submission_ids = r.json()
submission_dicts = []
for submission_id in submission_ids[:30]:
    # 对于每篇文章，都执行一个API调用
   url = f"https://hacker-news.firebaseio.com/v0/item/{submission_id}.json"
   r = requests.get(url)
   print(f"id: {submission_id}\tstatus: {r.status_code}")
   response_dict = r.json()
   # 对于每篇文章，都创建一个字典
   submission_dict = {
       'title': response_dict['title'],
       'hn_link': f"http://news.ycombinator.com/item?id={submission_id}",  
       'comments': response_dict['descendants'],
       }
   submission_dicts.append(submission_dict)
submission_dicts = sorted(submission_dicts, key=itemgetter('comments'), reverse=True)
for submission_dict in submission_dicts:
    print(f"\nTitle: {submission_dict['title']}")
    print(f"Discussion link: {submission_dict['hn_link']}")
    print(f"Comments: {submission_dict['comments']}")

titles, plot_dicts = [], []
for submission_dict in submission_dicts:
    title = submission_dict['title']
    title = f"<a href='{submission_dict['hn_link']}'>{title}</a>"
    owner = submission_dict['owner']
    description = submission_dict['description']
    plot_dict = {
        'value': submission_dict['comments'],
        'label': title, 
    }
    plot_dicts.append(plot_dict)
# 可视化
my_style = LS('#333366', base_style=LCS)
my_style.title_font_size = 24
my_style.label_font_size = 14
my_style.major_label_font_size = 18
my_config = {'scrollzoom': True}
my_layout = {
    'title': 'Most-Commented Python Projects on Hacker News', 
}       
fig = {'data': plot_dicts, 'layout': my_layout}
offline.plot(fig, filename='python_repos.html', config=my_config)
